package org.latestbit.smartobjects.perftests.server;

import java.util.Calendar;
import java.util.Random;
import java.util.concurrent.atomic.AtomicInteger;

import org.latestbit.smartobjects.core.ServerSkeleton;
import org.latestbit.smartobjects.exceptions.SmartBusSystemException;
import org.latestbit.smartobjects.perftests.IPerfTestServiceSyncSmartObject;
import org.latestbit.smartobjects.perftests.ITestStructureType;

public class PerfTestServiceSyncImpl implements IPerfTestServiceSyncSmartObject {
	private Thread statThread;
	private Random random;
	private boolean stopFlag = false;
	private long currentMeasureTime = Calendar.getInstance().getTimeInMillis();
	AtomicInteger tps = new AtomicInteger(0);
	AtomicInteger currentRequestQueueSize = new AtomicInteger(0);

	public PerfTestServiceSyncImpl(CommandLineOptions options) {
		random = new Random(Calendar.getInstance().getTimeInMillis());
		this.statThread = new Thread(new StatThread());
		this.statThread.start();
	}

	@Override
	public void destroy() {	
		stopFlag  = true;
		try {
			statThread.join();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	@Override
	public ITestStructureType testMethod(String paramStr, int paramInt,
			ITestStructureType paramStruct, ITestStructureType[] paramArray)
			throws SmartBusSystemException {
		tps.getAndAdd(1);
		long now = Calendar.getInstance().getTimeInMillis();
		if( now > currentMeasureTime + 5000 ) {
			currentRequestQueueSize.set(ServerSkeleton.getCurrentRequestContext().getSkeleton().getRequestQueueSize());
			currentMeasureTime = now;
		} 
		return paramArray[ random.nextInt( paramArray.length) ];
	}
	
	protected class StatThread implements Runnable {

		@Override
		public void run() {
			while(!stopFlag) {
				try {
					Thread.sleep(1000);
					System.out.println("TPS: "+ tps.getAndSet(0)+" ReqQueueSize: "+currentRequestQueueSize);
				} 
				catch (Exception e) {
					e.printStackTrace();
				}				
			}
		}
		
	}	

}
